package zb.wzby;

import javax.management.relation.RelationNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author wzby
 * @Date: 2022/8/10 15:11
 */
public class Ex1 {
    //启动十五个线程来计算

    volatile List<String> ls = new ArrayList<>();

    void math() {
        String str = Thread.currentThread().getName();
        System.out.printf(" %s启动计算中%n", str);
        String[] strs = new String[]{"", "+", "-"};
        Random rand = new Random();
        StringBuffer strb = new StringBuffer("1");
        Pattern p = Pattern.compile("(\\d+|-\\d+)");
        while (ls.size() != 1) {
            for (int i = 2; i < 10; i++)
                strb.append(String.format("%s%d", strs[rand.nextInt(strs.length)], i));
            String str2 = strb.toString();

            Matcher m = p.matcher(str2);
            List<Integer> ln = new ArrayList<>();
            while (m.find()) {
                ln.add(Integer.parseInt(m.group()));
            }
            int sum = ln.stream().reduce(0, Integer::sum);

            if (sum == 100 && !ls.contains(str2)) {
                ls.add(str2);
                System.out.printf("[%s]:%s = 100%n", str, str2);
            } else {
                strb.delete(1, strb.length());
            }
        }
        System.out.printf("%s结束 %n", str);
    }

    public static void main(String[] args) {
        var t = new Ex1();
        for (int i = 0; i < 15; i++)
            new Thread(t::math, "EX" + i).start();
    }
}
